<template>
  <div class="container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>搜索框</span>
        </div>
      </template>
      <el-input
          v-model="input"
          placeholder="请输入搜索内容"
          @keyup.enter="search1"
          class="input-with-select"
      >
        <template #append>
          <el-button icon="el-icon-search" @click="search1">搜索</el-button>
        </template>
      </el-input>
    </el-card>
    <el-card class="box-card mt-4">
      <template #header>
        <div class="card-header">
          <span>历史记录</span>
        </div>
      </template>
      <el-table :data="history" style="width: 100%">
        <el-table-column prop="userInput" label="用户输入" width="180"></el-table-column>
        <el-table-column prop="aiReply" label="AI回复"></el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import axios from 'axios';
import {ElMessage, ElLoading} from 'element-plus';
import {useRoute} from 'vue-router';

const route = useRoute();

const input = ref('');
const history = ref([]);
const loading = ref(null); // 使用null作为初始值，以便稍后创建ElLoading实例

if (route.query.data !== '') {
  input.value = route.query.data;
}

const search1 = () => {
  if (input.value === '') {
    ElMessage.error('请输入搜索内容');
  } else {
    // 创建ElLoading实例
    loading.value = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    const userInput = "用户输入：" + input.value;
    const aiReply = "";
    history.value.push({userInput, aiReply});
    axios.post('http://localhost:8000/app/xx/', {input: input.value})
        .then(res => {
          console.log(res.data);
          const aiReply = 'AI回复：' + res.data.data;
          history.value[history.value.length - 1].aiReply = aiReply;
          input.value = '';
        })
        .catch(error => {
          ElMessage.error('请求失败，请稍后再试');
          console.error(error);
        })
        .finally(() => {
          // 关闭ElLoading实例
          if (loading.value) {
            loading.value.close();
          }
        });
  }
};

// 页面加载时自动搜索
onMounted(() => {
  if (input.value) {
    search1();
  }
});
</script>

<style scoped>
.container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.box-card {
  width: 100%;
  max-width: 600px;
}

.mt-4 {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f0f0f0;
}

.input-with-select {
  width: 100%;
}
</style>